package com.ysncms.ext;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.repackaged.org.json.JSONObject;

public class ForgotPwdFilter implements Filter {
	
	private static final String HOST_NAME = Constants.APP_HOST_NAME;
	
	public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain)
	throws IOException {
		try {
			String path = ((HttpServletRequest) req).getRequestURI();
			if (path.startsWith("/ysn/sendPwd")) {
				String urlParameters = req.getParameter("email");
				String output = getURLOutput(HOST_NAME + "tnvrs/userservice/login/forgotpwd/", urlParameters);
				
				if (output != null) {
					if("success".equals(output)){
						String message = "Password Reset Successfully. \\nPlease check your email.";
						res.getWriter().write("<script>" +
												  " alert('"+message+"');" +
												  " window.location.href ='/';" +
												"</script>");
					} else {
						res.getWriter().write("<script>" +
								  " alert('Error while submitting form. Please try again.');" +
								  " window.location.href ='/';" +
								"</script>");
					}
				}
		 	} else if (path.startsWith("/ysn/resetPwd")){
				String newPassword = req.getParameter("password");
				
				String params = ((HttpServletRequest) req).getHeader("Referer");
				
				String uniqueKey = params.split("key=")[1];
				uniqueKey = uniqueKey.split("&")[0];
				
				JSONObject json = new JSONObject();
				json.put("uniqueKey", uniqueKey);
				json.put("plainTextPasswordReset", newPassword);
				
				String output = getURLOutput(HOST_NAME + "tnvrs/userservice/resetpassword2/", json.toString());
				if (output != null) {
					res.getWriter().write("<script>" +
							  " alert('"+output+"');" +
							  " window.location.href ='/';" +
							"</script>");
				}
			} else {
				// Just continue chain.
				chain.doFilter(req, res);
			}
		  } catch (Exception e) {
			  e.printStackTrace();
		  }
	}

	private String getURLOutput(String httpUrl, String data) throws Exception {
		URL url = new URL(httpUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setDoOutput(true);
		conn.setDoInput(true);

		conn.setReadTimeout(60 * 1000);
		conn.setConnectTimeout(60 * 1000);
		
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
		conn.setRequestProperty("charset", "utf-8");
		conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
		conn.setUseCaches (false);

 
		DataOutputStream wr = new DataOutputStream(conn.getOutputStream ());
		wr.writeBytes(data);
		wr.flush();
		wr.close();
		//conn.disconnect();
 
		BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
 
		String output = br.readLine();
		conn.disconnect();
		return output;
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
